<template>
  <button
    :disabled="disabled"
    class="z-button"
    :class="{[`icon-${iconPosition}`]: true, 'button-disabled': disabled}"
    @click="handleClick">
    <z-icon v-if="icon && !loading" :icon="icon" class="icon"></z-icon>
    <z-icon v-if="loading" icon="loading" class="icon loading"></z-icon>
    <div class="content">
      <slot></slot>
    </div>
  </button>
</template>

<script>
import zIcon from './icon'
export default {
  components: { zIcon },
  props: {
    icon: {
      default: '',
      type: String
    },
    loading: {
      default: false,
      type: Boolean
    },
    disabled: {
      default: false,
      type: Boolean
    },
    iconPosition: {
      default: 'left',
      type: String,
      validator (val) {
        if (val === 'left' || val === 'right') {
          return true
        } else {
          return false
        }
      }
    }
  },
  methods: {
    handleClick () {
      // 如果禁用了就不触发点击事件
      if (this.disabled) return
      this.$emit('click')
    }
  }

}
</script>

<style lang="scss" scoped>
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.z-button {
  font-size: 14px;
  height: 32px;
  padding: 0 1em;
  border-radius: 4px;
  border: 1px solid #999;
  background: white;
  vertical-align: middle;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  > .content {order: 2;}
  > .icon {order: 1; margin-right: .3em;}
  > .loading { animation: spin 2s infinite linear; }
  &:hover {
    border-color: #666;
  }
  &:active {
    background: rgba(0,0,0,.1);
  }
  &:focus {
    outline: none;
  }
}

.icon-right {
  > .content {order: 1;}
  > .icon {order: 2; margin-left: .3em; margin-right: 0;}
}
.button-disabled {
  background-color: rgba(0,0,0,.1);
  &:hover {
    cursor: not-allowed;
  }
}

</style>
